//
//  PywLoginMainView.m
//  PywSdk
//
//  Created by Jade on 4/7/16.
//  Copyright © 2016 zero. All rights reserved.
//

#import "PywLoginMainView.h"
#import "PywInputView.h"
#import "PywLoginDataSource.h"
#import "PywMasonry.h"
#import "UIImage+Pyw.h"
#import "PywNavgationController.h"
#import "PywLoginTopView.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywResourceUtils.h"
#import "PywUser.h"
#import "PywPassportUtils.h"
#import "PywIAPHelper.h"
#import "PywLoginApi.h"
#import "PywLoginAccountApi.h"
#import "PywPlatformMain.h"
#import "PywAccount.h"
#import "PywNewAccountApi.h"
#import "PywRegisterMainViewController.h"
#import "PywForgetCheckPhoneViewController.h"
#import "PywFastRegisterAccountController.h"
#import "PywPayPwdSetTradePwdViewController.h"
#import "MutableDictionary.h"
#import "PywAppInfo.h"
#import "PywFastRegisterApi.h"
#import "PywBuriedManager.h"

@interface PywLoginMainView()<UITextFieldDelegate>
{
    BOOL _isEncryptRSA;
}
@property (nonatomic,strong) PywLoginTopView *topView;
@property (nonatomic,strong) PywInputView *accountInputTF;
@property (nonatomic,strong) UITableView *accoutListTable;
@property (nonatomic,strong) PywInputView *passwordInputTF;
@property (nonatomic,strong) UIButton *enterButton;
@property (nonatomic,strong) UIButton *forgetButton;
@property (nonatomic,strong) UIButton *selectAccountButton;
@property (nonatomic,strong) UIButton *phoneRegisterButton; // 手机注册
@property (nonatomic,strong) UIButton *fastRegisterButton;  // 快速注册
@property (nonatomic,strong) UIView *lineView;

@property (nonatomic,strong) PywLoginDataSource *dataSource;//Table 的数据源
@property (nonatomic,strong) NSMutableArray *accountList;   //游戏账号列表
@property (nonatomic,strong) NSMutableArray *userList;      //平台账号列表

@property (nonatomic,strong) PywLoginApi *loginApi;
@property (nonatomic,strong) PywLoginAccountApi *loginAccoutApi;
@property (nonatomic,strong) PywNewAccountApi *accountNewApi;
@property (nonatomic,strong) PywFastRegisterApi *fastRegisterApi;
@end
@implementation PywLoginMainView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUp];
        NSLog(@"进入主登录页面");
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"退出主登录页面");
}

#pragma mark - setUp

- (void)setUp
{
    self.backgroundColor = [UIColor whiteColor];
    self.layer.cornerRadius = 20.f;
    self.layer.masksToBounds = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?NO:YES;
    self.alpha = 0;
    
    [self setUpUserList];
    
    [self addSubview:self.topView];
    [self addSubview:self.accountInputTF];
    [self addSubview:self.passwordInputTF];
    [self addSubview:self.enterButton];
    [self addSubview:self.forgetButton];
//    [self addSubview:self.phoneRegisterButton];
    
    [self addConstraints];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didRegisterAndLoginFail:)
                                                 name:@"didRegisterAndLoginFail"
                                               object:nil];
}

- (void)setUpUserList
{
    self.userList = [[NSMutableArray alloc] initWithArray:[PywPassportUtils passport]];
    if (self.userList.count == 0) {
        NSArray *accounts = [PywAppInfo sharedAppInfo].game_cache_account;
        for (NSString *userName in accounts) {
            PywUser *user = [[PywUser alloc] init];
            user.passport = userName;
            [self.userList addObject:user];
            [PywPassportUtils savePassport:user];
        }
    }
    
}


/**
 *  添加约束
 */
- (void)addConstraints
{
    WEAK_SELF;
    [self.topView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.mas_left);
        make.top.mas_equalTo(weakSelf.mas_top);
        make.right.mas_equalTo(weakSelf.mas_right);
        CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.1:0.17;
        make.height.mas_equalTo(weakSelf.mas_height).multipliedBy(height);
    }];
    
    [self.accountInputTF mas_makeConstraints:^(PywMASConstraintMaker *make) {
        
        make.centerX.offset(0);
        make.top.mas_equalTo(weakSelf.topView.mas_bottom).offset(15);
        make.width.mas_equalTo(weakSelf.mas_width).multipliedBy(0.9);
        make.height.mas_equalTo(weakSelf.mas_height).multipliedBy(0.15);
    }];
    
    [self.passwordInputTF mas_makeConstraints:^(PywMASConstraintMaker *make) {
        
        make.centerX.offset(0);
        make.top.mas_equalTo(weakSelf.accountInputTF.mas_bottom).offset(10);
        make.width.mas_equalTo(weakSelf.mas_width).multipliedBy(0.9);
        make.height.mas_equalTo(weakSelf.accountInputTF.mas_height);
    }];
    
    [self.enterButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        
        make.centerX.offset(0);
        make.top.mas_equalTo(weakSelf.passwordInputTF.mas_bottom).offset(10);
        make.width.mas_equalTo(weakSelf.passwordInputTF);
        make.height.mas_equalTo(40);
    }];
    
    [self.forgetButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        
        make.top.mas_equalTo(weakSelf.enterButton.mas_bottom).offset(10);
        make.left.mas_equalTo(weakSelf.enterButton.mas_left).offset(2);
        make.height.equalTo(weakSelf.mas_height).multipliedBy(0.10);
    }];
    
    /*
    [self.phoneRegisterButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.equalTo(weakSelf.forgetButton.mas_top);
        make.right.mas_equalTo(weakSelf.enterButton.mas_right).offset(-2);
        make.height.equalTo(weakSelf.forgetButton.mas_height);
    }];
    
    if ([PywPlatformMain sharedPlatformMain].is_fastRegister) {
        [self addSubview:self.lineView];
        [self addSubview:self.fastRegisterButton];
        
        [self.lineView mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.centerY.equalTo(weakSelf.phoneRegisterButton.mas_centerY);
            make.right.equalTo(weakSelf.phoneRegisterButton.mas_left).offset(-4);
            make.width.mas_equalTo(1);
            make.height.mas_equalTo(13);
        }];
        
        [self.fastRegisterButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.top.equalTo(weakSelf.forgetButton.mas_top);
            make.right.mas_equalTo(weakSelf.lineView.mas_left).offset(-4);
            make.height.equalTo(weakSelf.forgetButton.mas_height);
        }];
    }
    */
    
    /**
     *  最高优先级，手机注册开关
     *
     *  场景：
     *  1. 手机注册，开：{快速注册，开，显示快速注册；快速注册，关，隐藏快速注册；}
     *  2. 手机注册，关：{快速注册与手机注册，均隐藏}
     */
    if ([PywPlatformMain sharedPlatformMain].is_reg_open == YES) {
        if ([PywPlatformMain sharedPlatformMain].is_fastRegister == YES) {
            [self addSubview:self.lineView];
            [self addSubview:self.fastRegisterButton];
            [self addSubview:self.phoneRegisterButton];
            
            [self.lineView mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.centerY.equalTo(weakSelf.phoneRegisterButton.mas_centerY);
                make.right.equalTo(weakSelf.phoneRegisterButton.mas_left).offset(-4);
                make.width.mas_equalTo(1);
                make.height.mas_equalTo(13);
            }];
            
            [self.fastRegisterButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.top.equalTo(weakSelf.forgetButton.mas_top);
                make.right.mas_equalTo(weakSelf.lineView.mas_left).offset(-4);
                make.height.equalTo(weakSelf.forgetButton.mas_height);
            }];
            
            [self.phoneRegisterButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.top.equalTo(weakSelf.forgetButton.mas_top);
                make.right.mas_equalTo(weakSelf.enterButton.mas_right).offset(-2);
                make.height.equalTo(weakSelf.forgetButton.mas_height);
            }];
        }else{
            
            [self addSubview:self.phoneRegisterButton];
            [self.phoneRegisterButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
                make.top.equalTo(weakSelf.forgetButton.mas_top);
                make.right.mas_equalTo(weakSelf.enterButton.mas_right).offset(-2);
                make.height.equalTo(weakSelf.forgetButton.mas_height);
            }];
        }
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    /**
     *  Table 的约束
     */
    if (!CGRectEqualToRect(self.frame, CGRectZero)) {
        if (!_accoutListTable) {
            [self addSubview:self.accoutListTable];
            __weak typeof(self) weakSelf = self;
            [self.accoutListTable mas_makeConstraints :^(PywMASConstraintMaker *make) {
                make.centerX.offset(0);
                make.top.mas_equalTo(weakSelf.accountInputTF.mas_bottom);
                make.width.mas_equalTo(weakSelf.accountInputTF.mas_width);
                make.height.mas_equalTo(0);
            }];
        }
        
    }
}

#pragma mark - getter
/**
 *  快速注册Api
 *
 *  @return <#return value description#>
 */
- (PywFastRegisterApi *)fastRegisterApi{
    if (!_fastRegisterApi) {
        _fastRegisterApi = [PywFastRegisterApi manager];
    }
    return _fastRegisterApi;
}

/**
 *  顶部
 *
 */
- (PywLoginTopView *)topView
{
    if (!_topView) {
        _topView = [[PywLoginTopView alloc] init];
    }
    return _topView;
}


/**
 *  账号输入框
 *
 */
- (PywInputView *)accountInputTF
{
    if (!_accountInputTF) {
        
        _accountInputTF = [[PywInputView alloc] init];
        [_accountInputTF addTarget:self
                            action:@selector(accountTextFieldChange:)
                  forControlEvents:UIControlEventEditingDidBegin];
        _accountInputTF.delegate = self;
        [_accountInputTF.inputTF setAccessibilityIdentifier:@"login_account"];
        _accountInputTF.placeholder = @"通行证/游戏账号";
        _accountInputTF.rightView = self.selectAccountButton;
        _accountInputTF.leftView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"icon_user_normal"]];
        if (self.userList.count > 0) {
            PywUser *user = self.userList.firstObject;
            _accountInputTF.text = user.passport;
        }
    }
    return _accountInputTF;
}

- (UITableView *)accoutListTable
{
    if (!_accoutListTable) {
        _accoutListTable = [[UITableView alloc] init];
        _accoutListTable.tableFooterView = [[UIView alloc] init];
        _accoutListTable.dataSource = self.dataSource;
        _accoutListTable.delegate = self.dataSource;
        _accoutListTable.layer.borderWidth = 1;
        _accoutListTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _accoutListTable.layer.borderColor = [UIColor colorWithRed:237/255.f
                                                              green:237/255.f
                                                               blue:237/255.f
                                                              alpha:1.f].CGColor;
    }
    return _accoutListTable;
}

/**
 *  密码输入框
 */
- (PywInputView *)passwordInputTF{
    
    if (!_passwordInputTF) {
        
        _passwordInputTF = [[PywInputView alloc] init];
        [_passwordInputTF setSecureTextEntry:YES];
        _passwordInputTF.delegate = self;
        [_passwordInputTF.inputTF setAccessibilityIdentifier:@"login_pwsd"];
        _passwordInputTF.leftView = [[UIImageView alloc] initWithImage:[UIImage imageWithName:@"icon_password_normal"]];;
        _passwordInputTF.placeholder = @"请输入密码";
        if (self.userList.count > 0) {
            PywUser *user = self.userList.firstObject;
            _passwordInputTF.text = user.password;
        }
    }
    return _passwordInputTF;
}

/**
 *  进入游戏按钮
 */
- (UIButton *)enterButton{
    
    if (!_enterButton) {
        
        _enterButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _enterButton.layer.cornerRadius = 20;
        [_enterButton setTitle:@"进入游戏" forState:UIControlStateNormal];
        _enterButton.backgroundColor = [UIColor colorWithRed:255/255.f green:188/255.f blue:0/255.f alpha:1.f];
        [_enterButton setTitleColor:[UIColor blackColor]
                           forState:UIControlStateHighlighted];
        [_enterButton setTitleColor:[UIColor whiteColor]
                           forState:UIControlStateNormal];
        [_enterButton addTarget:self
                         action:@selector(selectLoginButton:)
               forControlEvents:UIControlEventTouchUpInside];
        [_enterButton setAccessibilityIdentifier:@"login_btn"];
    }
    return _enterButton;
}

/**
 *  忘记密码
 */
- (UIButton *)forgetButton{
    
    if (!_forgetButton) {
        
        _forgetButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_forgetButton.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
        [_forgetButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
        [_forgetButton setTitleColor:[UIColor grayColor]
                            forState:UIControlStateNormal];
        [_forgetButton setTitleColor:[UIColor blackColor]
                            forState:UIControlStateHighlighted];
        [_forgetButton setTitle:@"忘记密码?"
                       forState:UIControlStateNormal];
        [_forgetButton addTarget:self
                          action:@selector(selectForgetButton:)
                forControlEvents:UIControlEventTouchUpInside];
        [_forgetButton setAccessibilityIdentifier:@"login_forgotpswd"];
    }
    return _forgetButton;
}

/**
 *  注册按钮
 */
- (UIButton *)phoneRegisterButton{
    
    if (!_phoneRegisterButton) {
        
        _phoneRegisterButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_phoneRegisterButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_phoneRegisterButton.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
        [_phoneRegisterButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [_phoneRegisterButton setTitle:@"手机注册"
                         forState:UIControlStateNormal];
        [_phoneRegisterButton setTitleColor:[UIColor blackColor]
                              forState:UIControlStateHighlighted];
        [_phoneRegisterButton addTarget:self
                            action:@selector(selectPhoneRegisterButton:)
                  forControlEvents:UIControlEventTouchUpInside];
        [_phoneRegisterButton setAccessibilityIdentifier:@"login_phonereg"];
    }
    return _phoneRegisterButton;
}

/**
 *  选择历史账号按钮
 */
- (UIButton *)selectAccountButton{
    if (!_selectAccountButton) {
        _selectAccountButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _selectAccountButton.frame = CGRectMake(0, 0, 25, 25);
        [_selectAccountButton setImage:[UIImage imageWithName:@"icon_login_drop_normal"]
                              forState:UIControlStateNormal];
        [_selectAccountButton addTarget:self
                                 action:@selector(selectAccountListTable:)
                       forControlEvents:UIControlEventTouchUpInside];
//        self.passwordInputTF.rightView = _selectAccountButton;
    }
    return _selectAccountButton;
}

- (UIButton *)fastRegisterButton
{
    if (!_fastRegisterButton) {
        _fastRegisterButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_fastRegisterButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_fastRegisterButton.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
        [_fastRegisterButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [_fastRegisterButton setTitle:@"快速注册"
                         forState:UIControlStateNormal];
        [_fastRegisterButton setTitleColor:[UIColor blackColor]
                              forState:UIControlStateHighlighted];
        [_fastRegisterButton addTarget:self
                            action:@selector(selectFastRegisterButton:)
                  forControlEvents:UIControlEventTouchUpInside];
        [_fastRegisterButton setAccessibilityIdentifier:@"login_fastreg"];
    }
    return _fastRegisterButton;
}

- (UIView *)lineView
{
    if (!_lineView) {
        _lineView = [UIView new];
        _lineView.backgroundColor = [UIColor grayColor];
    }
    return _lineView;
}

/**
 *  TableView 的数据源
 *
 */
- (PywLoginDataSource *)dataSource
{
    if (!_dataSource) {
        WEAK_SELF;
        NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:self.userList.count];
        for (PywUser *user in self.userList) {
            [array addObject:user.passport];
        }
        
        _dataSource = [PywLoginDataSource createTableDataSourceWithDataList:array isEdit:YES didSelectRow:^(NSIndexPath *indexPath) {
            [weakSelf endEditing:YES];
            PywUser *user = weakSelf.userList[indexPath.row];
            weakSelf.accountInputTF.text = user.passport;
            weakSelf.passwordInputTF.text = user.password;
            [weakSelf hideTable];
            [weakSelf animationRoatateDropArrow:weakSelf.selectAccountButton.selected];
        }];
        _dataSource.deleteCacheCompletion = ^(NSString *userName) {
            [weakSelf deleteCacheAccount:userName];
        };
    }
    
    return _dataSource;
}



#pragma mark - Action Medthod
/**
 *  删除登录列表缓存
 *
 *  @param userName <#userName description#>
 */
- (void)deleteCacheAccount:(NSString *)userName
{
    for (PywUser *user in self.userList) {
        if ([user.passport isEqualToString:userName]) {
            [self.userList removeObject:user];
            break;
        }
    }
    [PywPassportUtils savePassportList:self.userList];
    if ([self.accountInputTF.text isEqualToString:userName]) {
        self.accountInputTF.text = @"";
        self.passwordInputTF.text = @"";
    }
    [self.accoutListTable reloadData];
    if (self.userList.count == 0) {
        [self hideTable];
        [self animationRoatateDropArrow:YES];
    }
}

/**
 *  输入账号下拉列表消失
 *
 *  @param inputTF <#inputTF description#>
 */
- (void)accountTextFieldChange:(PywInputView *)inputTF
{
    [self hideTable];
}

/**
 *  点击进入游戏
 *
 *  @param sender <#sender description#>
 */
- (void)selectLoginButton:(UIButton *)sender
{
    [self endEditing:YES];
    NSLog(@"主登陆页面，点击“进入游戏”按钮");
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"1" actionSn:@"3" typeSn:@"3"];
    
    [self requestLogin:self.accountInputTF.text loginPassword:self.passwordInputTF.text];
}

/**
 *  点击忘记密码
 *
 *  @param sender <#sender description#>
 */
- (void)selectForgetButton:(UIButton *)sender
{
    [self endEditing:YES];
    NSLog(@"主登陆页面，点击“忘记密码”按钮");
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"1" actionSn:@"6" typeSn:@"3"];

    PywForgetCheckPhoneViewController *checkPhoneVC = [[PywForgetCheckPhoneViewController alloc] init];
    PywNavgationController *nav = [[PywNavgationController alloc] initWithRootViewController:checkPhoneVC];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:NULL];
}

/**
 *  点击 手机注册
 *
 *  @param sender <#sender description#>
 */
- (void)selectPhoneRegisterButton:(UIButton *)sender
{
    [self endEditing:YES];
    NSLog(@"主登陆页面，点击“手机注册”按钮");
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"1" actionSn:@"5" typeSn:@"3"];

    PywRegisterMainViewController *verifyVC = [[PywRegisterMainViewController alloc] init];
    PywNavgationController *nav = [[PywNavgationController alloc] initWithRootViewController:verifyVC];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:NULL];
}
/**
 *  点击 快速注册
 *
 *  @param sender <#sender description#>
 */
- (void)selectFastRegisterButton:(UIButton *)sender
{
    [self endEditing:YES];
    NSLog(@"主登陆页面，点击“快速注册”按钮");
    [[PywBuriedManager manager] saveUserActionDataWithPageSn:@"1" actionSn:@"4" typeSn:@"3"];

    [self.fastRegisterApi requestFastRegisterWithFlag:FastRegisterFlag_Register success:^(NSString *status, id anyObjct) {
        
        NSString *account = [NSString stringWithFormat:@"%@",anyObjct[@"account"]];
        NSString *password = [NSString stringWithFormat:@"%@",anyObjct[@"password"]];
        
        PywFastRegisterAccountController *fastRegisterVC = [[PywFastRegisterAccountController alloc] initWithAccount:account password:password];
        PywNavgationController *nav = [[PywNavgationController alloc] initWithRootViewController:fastRegisterVC];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:YES completion:NULL];
    } fail:^(NSError *error) {
        
    }];
}

/**
 *  选择历史账号列表
 *
 *  @param sender <#sender description#>
 */
- (void)selectAccountListTable:(UIButton *)sender
{
    [self endEditing:YES];
    [self animationRoatateDropArrow:sender.selected];
    
    sender.selected = !sender.selected;
    sender.selected?[self showTable]:[self hideTable];
    
}


#pragma mark - 新建平台账号成功--登录失败后

- (void)didRegisterAndLoginFail:(NSNotification *)aNotification
{
    self.userList = [[NSMutableArray alloc] initWithArray:[PywPassportUtils passport]];
    if (self.userList.count > 0) {
        PywUser *user = self.userList.firstObject;
        self.accountInputTF.text = user.passport;
        self.passwordInputTF.text = user.password;
    }

}


#pragma mark - Public
/**
 *  添加到父视图
 *
 *  @param superView <#superView description#>
 */
- (void)add2SuperView:(UIView *)superView
{
    [superView addSubview:self];
    [self mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.center.offset(0);
        NSInteger viewWidth = [UIScreen mainScreen].bounds.size.width >
        [UIScreen mainScreen].bounds.size.height ?
        [UIScreen mainScreen].bounds.size.height :
        [UIScreen mainScreen].bounds.size.width;
        viewWidth = MIN(viewWidth, 500);
        make.width.equalTo(@(viewWidth * 0.85));
        if (viewWidth%320 == 0 || viewWidth%480 == 0) {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.65:0.75;
            make.height.equalTo(@(viewWidth * height));
        }else {
            CGFloat height  = [PywAppInfo sharedAppInfo].appType == AppTypeFQ?0.58:0.65;
            make.height.equalTo(@(viewWidth * height));
        }
    }];
}


/**
 *  注册后登录游戏账号
 *
 *  @param loginPassport <#loginPassport description#>
 */
- (void)reloadLoginText:(NSString *)loginPassport password:(NSString *)password
{
    self.accountInputTF.text = loginPassport;
    
    if (password.length > 0) {
        self.passwordInputTF.text = password;
        [self selectLoginButton:nil];
    } else {
        self.passwordInputTF.text = @"";
        [self.passwordInputTF becomeFirstResponder];
    }
}

/**
 *  自动登录通行证账号
 */
- (void)autoLoginPassport
{
    [self requestLogin:[PywPlatformMain sharedPlatformMain].userName loginPassword:[PywPlatformMain sharedPlatformMain].passport_pwd];
}

#pragma mark - Request



/**
 *  请求登录页面
 *
 *  @param loginName     登录账号
 *  @param loginPassword 登录密码
 */
- (void)requestLogin:(NSString *)loginName loginPassword:(NSString *)loginPassword
{
    loginName = [loginName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    loginPassword = [loginPassword stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (loginName.length == 0) {
        [PywMBProgressHUD showError:@"请输入账号！"];
        return;
    }else if (loginPassword.length == 0) {
        [PywMBProgressHUD showError:@"请输入密码！"];
        return;
    }
    MutableDictionary *dict = [[MutableDictionary alloc] init];
    [dict setObject:loginName forKey:@"name"];
    [dict setObject:loginPassword forKey:@"password"];
    [dict setObject:[NSNumber numberWithBool:_isEncryptRSA] forKey:@"isEncryptRSA"];
    
    WEAK_SELF;
    self.loginApi = [PywLoginApi manager];
    [self.loginApi requestLoginWithParams:dict success:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        /**
         *  登录成功回调
         */
        NSInteger account_type = [status integerValue];
        if (account_type == 1) {//平台账号登录
            if (anyObjct) {
                strongSelf.accountList = [[NSMutableArray alloc] init];
                [strongSelf.accountList setArray:anyObjct];
            }
            //不是切换账号登录就直接登录第一个账号，如果没有账号就新建账号
            NSString *loginAccount = [PywPlatformMain sharedPlatformMain].changeAccount;
            if (strongSelf.accountList.count == 0) {
                [strongSelf requestNewLoginGameAccount];
            }else {
                if (loginAccount.length == 0) {
                    PywAccount *account = [strongSelf.accountList firstObject];
                    loginAccount = account.account;
                }
                [strongSelf loginAccountNoPwd:loginAccount];
            }
            
        }else {//游戏账号登录
            [PywPlatformMain sharedPlatformMain].is_game_fast_login = YES;
            if (strongSelf.loginPassportCompletion) {
                strongSelf.loginPassportCompletion(strongSelf,nil);
            }
        }
        
    } fail:^(NSError *error) {
        if (self.loginPassportFail) {
            self.loginPassportFail(self);
        }
    }];
}



/**
 *  免密码登录
 */
- (void)loginAccountNoPwd:(NSString *)account
{
    self.loginAccoutApi = [PywLoginAccountApi manager];
    WEAK_SELF;
    [self.loginAccoutApi requestLoginAccount:account success:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        if (strongSelf.loginPassportCompletion) {
            strongSelf.loginPassportCompletion(strongSelf,strongSelf.accountList);
        }
    } fail:^(NSError *error) {
        STRONG_SELF(weakSelf);
        if (strongSelf.loginPassportFail) {
            strongSelf.loginPassportFail(strongSelf);
        }
        switch (error.code) {
            case 1005:
            {
                [PywMBProgressHUD showError:@"游戏账号错误" toView:[UIApplication sharedApplication].keyWindow];
            }
                break;
            default:
            {
                [PywMBProgressHUD showError:@"登录失败，请重新登录" toView:[UIApplication sharedApplication].keyWindow];
            }
                break;
        }
    }];
}

/**
 *  新建游戏账号
 */
- (void)requestNewLoginGameAccount
{
    self.accountNewApi = [PywNewAccountApi manager];
    WEAK_SELF;
    [self.accountNewApi requestNewAccount:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        if (strongSelf.loginPassportCompletion) {
            strongSelf.loginPassportCompletion(strongSelf,strongSelf.accountList);
        }
    } fail:^(NSError *error) {
        STRONG_SELF(weakSelf);
        if (strongSelf.loginPassportFail) {
            strongSelf.loginPassportFail(strongSelf);
        }
        [PywMBProgressHUD showError:@"登录失败，请重新登录" toView:[UIApplication sharedApplication].keyWindow];
    }];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == self.accountInputTF.inputTF) {
        self.accountInputTF.text = textField.text;
    }else if (textField == self.passwordInputTF.inputTF) {
        self.passwordInputTF.text = textField.text;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.passwordInputTF.inputTF && string.length > 0) {
        _isEncryptRSA = YES;
    }
    return YES;
}

#pragma mark - Private
/**
 *  旋转选择账号列表按钮
 *
 *  @param isRotate <#isRotate description#>
 */
- (void)animationRoatateDropArrow:(BOOL)isRotate
{
    CATransform3D tranfrom = isRotate?CATransform3DIdentity:CATransform3DMakeRotation(M_PI, 0, 0, 1);
    [UIView animateWithDuration:.2f
                     animations:^{
                         _selectAccountButton.layer.transform = tranfrom;
                     } completion:^(BOOL finished) {
                         
                     }];
}

/**
 *  显示Table
 *
 */
- (void)showTable
{
    __weak typeof(self) weakSelf = self;
    CGRect accountFrame = self.accoutListTable.frame;
    accountFrame.size.height = 90.f;
    [UIView animateWithDuration:.2f
                          delay:0.f
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         weakSelf.accoutListTable.frame = accountFrame;
                     } completion:^(BOOL finished) {
                         weakSelf.selectAccountButton.selected = YES;
                     }];
    
}

/**
 *  隐藏Table
 */
- (void)hideTable
{
    __weak typeof(self) weakSelf = self;
    CGRect accountFrame = self.accoutListTable.frame;
    accountFrame.size.height = 0.f;
    [UIView animateWithDuration:.2f
                          delay:0.f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         weakSelf.accoutListTable.frame = accountFrame;
                     } completion:^(BOOL finished) {
                         weakSelf.selectAccountButton.selected = NO;
                     }];
}




-(void)addBottomBorderWithColor:(UIColor *)color
                       andWidth:(CGFloat) borderWidth
{
    CALayer *border = [CALayer layer];
    border.backgroundColor = color.CGColor;
    border.frame = CGRectMake(0, self.frame.size.height - borderWidth, self.frame.size.width, borderWidth);
    [self.layer addSublayer:border];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}
@end
